package com.ziyucoding.springboot.labs.lab10.seatdemo.tccscfeign.productservice.dao;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.springframework.stereotype.Repository;

/**
 * 商品 DAO
 *
 * @author ziyucoding
 * @date 2022-11-06
 **/
@Mapper
@Repository
public interface ProductDao {

    /**
     * 获取库存
     *
     * @param productId
     * @return Integer
     **/
    @Select("SELECT stock FROM product WHERE id = #{productId}")
    Integer getStock(@Param("productId") Long productId);

    /**
     * 获取冻结库存
     *
     * @param productId
     * @return Integer
     **/
    @Select("SELECT frozen FROM product WHERE id = #{productId}")
    Integer getFrozenStock(@Param("productId") Long productId);

    /**
     * 冻结库存
     *
     * @param productId
     * @param amount
     * @return int
     **/
    @Update("UPDATE product SET stock = stock - #{amount}, frozen = frozen + #{amount}  WHERE id = #{productId} AND stock >= #{amount}")
    int frozenStock(@Param("productId") Long productId, @Param("amount") Integer amount);

    /**
     * 释放冻结的库存
     *
     * @param productId
     * @param amount
     * @return int
     **/
    @Update("UPDATE product SET frozen = frozen - #{amount}  WHERE id = #{productId} AND frozen >= #{amount}")
    int cleanFrozenStock(@Param("productId") Long productId, @Param("amount") Integer amount);

    /**
     * 回滚冻结的库存
     *
     * @param productId
     * @param amount
     * @return int
     **/
    @Update("UPDATE product SET  stock = stock + #{amount}, frozen = frozen - #{amount}  WHERE id = #{productId} AND frozen >= #{amount}")
    int rollbackFrozenStock(@Param("productId") Long productId, @Param("amount") Integer amount);

}
